/*
 * Copyright (c) 2015 The Jupiter Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ferry.transport.netty.provider;

import com.ferry.common.util.concurrent.NamedThreadFactory;
import com.ferry.transport.api.domain.Protocol;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.util.HashedWheelTimer;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.ThreadFactory;


/**
 *  NettyAcceptor
 */
public abstract class NettyAcceptor implements TcpAcceptor {

    protected final SocketAddress localAddress;

    /**
     * netty 时间轮
     */
    protected final HashedWheelTimer timer = new HashedWheelTimer(new NamedThreadFactory("acceptor.timer", true));

    //boss 线程数
    private final int nBosses;
    //工作线程数
    private final int nWorkers;

    //服务启动类
    private ServerBootstrap serverBootstrap;
    //boss线程组
    private EventLoopGroup boss;
    //worker 线程组
    private EventLoopGroup worker;
    //请求处理器
    private ProviderProcessor processor;

    public NettyAcceptor(SocketAddress localAddress, int nWorkers) {
        this(localAddress, 1, nWorkers);
    }

    public NettyAcceptor(SocketAddress localAddress, int nBosses, int nWorkers) {
        this.localAddress = localAddress;
        this.nBosses = nBosses;
        this.nWorkers = nWorkers;
    }

    protected void init() {
        ThreadFactory bossFactory = bossThreadFactory("ferry.acceptor.boss");
        ThreadFactory workerFactory = workerThreadFactory("ferry.acceptor.worker");
        boss = initEventLoopGroup(nBosses, bossFactory);
        worker = initEventLoopGroup(nWorkers, workerFactory);

        serverBootstrap = new ServerBootstrap().group(boss, worker);
    }

    @Override
    public SocketAddress localAddress() {
        return localAddress;
    }

    @Override
    public int bindPort() {
        if (!(localAddress instanceof InetSocketAddress)) {
            throw new UnsupportedOperationException("Unsupported address type to get port");
        }
        return ((InetSocketAddress) localAddress).getPort();
    }

    @Override
    public Protocol protocol() {
        return Protocol.TCP;
    }

    @Override
    public ProviderProcessor processor() {
        return processor;
    }

    @Override
    public void withProcessor(ProviderProcessor processor) {
        setProcessor(this.processor = processor);
    }

    @Override
    public void shutdownGracefully() {
        boss.shutdownGracefully().syncUninterruptibly();
        worker.shutdownGracefully().syncUninterruptibly();
        timer.stop();
        if (processor != null) {
            processor.shutdown();
        }
    }

    protected ThreadFactory bossThreadFactory(String name) {
        return new DefaultThreadFactory(name, Thread.MAX_PRIORITY);
    }

    protected ThreadFactory workerThreadFactory(String name) {
        return new DefaultThreadFactory(name, Thread.MAX_PRIORITY);
    }


    protected ServerBootstrap serverBootstrap() {
        return serverBootstrap;
    }

    protected EventLoopGroup boss() {
        return boss;
    }

    protected EventLoopGroup worker() {
        return worker;
    }

    protected void setProcessor(ProviderProcessor processor) {
    }

    protected abstract ChannelFuture bind(SocketAddress localAddress);

    protected abstract EventLoopGroup initEventLoopGroup(int nThreads, ThreadFactory tFactory);


}
